package com.histone.lilian.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.histone.lilian.entity.SysUser;
import com.histone.lilian.mapper.SysUserMapper;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.Authorization;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义用户名密码登录
 */
@Component
public class CustomAuthorizationInterceptor implements AuthorizationInterceptor {

    private final SysUserMapper sysUserMapper;

    public CustomAuthorizationInterceptor(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return false;
    }

    /**
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        System.out.println("收到token" + token + "当前id" + StpUtil.getLoginId());
        Object loginId = StpUtil.getLoginId();
        if (loginId != null) {
            SysUser sysUser = (SysUser) StpUtil.getSessionByLoginId(loginId).get("userInfo");
            return new MagicUser(sysUser.getId(), sysUser.getUsername(), token);
        }
        throw new MagicLoginException("token无效");
    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser != null) {
            if (!"0".equals(sysUser.getStatus())) {
                throw new MagicLoginException("该账号已被停用");
            }
            if (BCrypt.checkpw(password, sysUser.getPassword())) {
                // 系统登录后，Magic Api仍然需要登录一次。token不需要重复生成
                String token = StpUtil.getTokenValueByLoginId(sysUser.getId());
                if (StrUtil.isBlank(token)) {
                    sysUser.setPassword(null);
                    StpUtil.login(sysUser.getId());
                    StpUtil.getSessionByLoginId(sysUser.getId(), true)
                            .set("username", sysUser.getUsername())
                            .set("userInfo", sysUser);
                    token = StpUtil.getTokenValue();
                }

                return new MagicUser(sysUser.getId(), sysUser.getUsername(), token);
            }
        }

        throw new MagicLoginException("用户名或密码不正确");
    }

    /**
     * 是否拥有页面按钮的权限
     */
    @Override
    public boolean allowVisit(MagicUser magicUser, HttpServletRequest request, Authorization authorization) {
        if (StpUtil.hasRole("admin")) {
            return true;
        }
        switch (authorization) {
            case VIEW:
                return StpUtil.hasPermission("magic:api:list");
            case DELETE:
                return StpUtil.hasPermission("magic:api:remove");
            default:
                return StpUtil.hasPermission("magic:api:edit");
        }
    }

}
